﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using YY.Admin.Core.Models;

namespace YY.Admin.Services
{
    public class AuthService : IAuthService
    {
        private User? _currentUser;
        public User? CurrentUser => _currentUser;
        public event EventHandler<User?>? UserChanged;

        public async Task<LoginResponse> LoginAsync(LoginRequest request)
        {
            try
            {
                // 模拟异步登录验证
                await Task.Delay(1000);

                // 这里你可以调用数据库验证
                // 示例：简单的用户名密码验证
                if (request.Username == "admin" && request.Password == "123456")
                {
                    _currentUser = new User
                    {
                        Id = 1,
                        Username = request.Username,
                        Email = "admin@example.com",
                        Role = "Administrator",
                        CreatedAt = DateTime.Now.AddYears(-1),
                        LastLoginAt = DateTime.Now,
                        IsActive = true
                    };

                    UserChanged?.Invoke(this, _currentUser);

                    return new LoginResponse
                    {
                        Success = true,
                        Message = "登录成功",
                        User = _currentUser,
                        Token = GenerateToken()
                    };
                }
                else
                {
                    return new LoginResponse
                    {
                        Success = false,
                        Message = "用户名或密码错误"
                    };
                }
            }
            catch (Exception ex)
            {
                return new LoginResponse
                {
                    Success = false,
                    Message = $"登录失败：{ex.Message}"
                };
            }
        }

        public async Task LogoutAsync()
        {
            await Task.Delay(100);
            _currentUser = null;
            UserChanged?.Invoke(this, null);
        }

        public async Task<bool> IsAuthenticatedAsync()
        {
            await Task.Delay(50);
            return _currentUser != null;
        }

        private string GenerateToken()
        {
            var bytes = new byte[32];
            using var rng = RandomNumberGenerator.Create();
            rng.GetBytes(bytes);
            return Convert.ToBase64String(bytes);
        }
    }
}
